package com.xiaobai.units;

import com.xiaobai.common.CommonMoon;
import lombok.SneakyThrows;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 月亮工具类
 * @author: 小白白
 * @create: 2021-09-14
 **/

public class MoonUnit {

    private StringRedisTemplate stringRedisTemplate;

    private CloseableHttpClient httpclient = HttpClients.createDefault();

    private final String[] dog = {
            "https://api.oick.cn/dog/api.php"
    };

    private final String[] soup = {
            "https://api.oick.cn/dutang/api.php"
    };

    private final String[] love = {
            "https://api.1314.cool/words/api.php"
    };

    public static interface UU {
        String adapter(String str);
    }

    public MoonUnit(StringRedisTemplate stringRedisTemplate, String key, int urlIndex, int count, UU u) {
        this(stringRedisTemplate,key,urlIndex,count,u,1);
    }

    @SneakyThrows
    public MoonUnit(StringRedisTemplate stringRedisTemplate, String key, int urlIndex, int count, UU u, int threadCount) {
        this.stringRedisTemplate = stringRedisTemplate;
        String url = key.equals(CommonMoon.MOON_DOG) ?
                dog[urlIndex] :
                key.equals(CommonMoon.MOON_LOVE) ? love[urlIndex] : soup[urlIndex];
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
        for (int i = 0; i < threadCount; i++) {
            executorService.execute(()->{
                this.updateMoon(key, url, count, u);
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
    }

    /**
     * 总体
     */
    @SneakyThrows
    private void updateMoon(String key, String url, int count, UU u) {
        HttpGet httpGet = new HttpGet(url);
        Set<String> set = new HashSet<>();
        CloseableHttpResponse execute = null;
        while (count > 0) {
            execute = httpclient.execute(httpGet);
            String content;
            try {
                content = EntityUtils.toString(execute.getEntity());
            }finally {
                execute.close();
            }
            content = u.adapter(content);
            set.add(content);
            count--;
        }
        String[] arr = set.toArray(new String[]{});
        stringRedisTemplate.opsForSet().add(key, arr);
    }

}
